package com.yao2san.sim.storage.client.core.downloader;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.yao2san.sim.storage.client.config.AliOssProperties;
import com.yao2san.sim.storage.client.config.SimStorageClientProperties;
import com.yao2san.sim.storage.client.core.enums.StorageType;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author wxg
 **/
public class AliOssDownloader extends AbstractDownloader {

    private final AliOssProperties aliOssProperties;
    private final OSS ossClient;

    public AliOssDownloader(OSS ossClient, AliOssProperties aliOssProperties) {
        this.aliOssProperties = aliOssProperties;
        this.ossClient = ossClient;
    }

    @Override
    public void download(String object, OutputStream out) throws IOException {
        String bucket = aliOssProperties.getBucket();
        OSSObject ossObject = ossClient.getObject(bucket, object);
        IOUtils.copy(ossObject.getObjectContent(), out);
        ossObject.close();
    }

    @Override
    public String url(String object) {
        return url(object, false);
    }

    @Override
    public String url(String object, boolean preSigned) {
        if (preSigned) {
            Date expiration = Date.from(LocalDateTime.now().plusMinutes(30).atZone(ZoneId.systemDefault()).toInstant());
            return ossClient.generatePresignedUrl(aliOssProperties.getBucket(), object, expiration, HttpMethod.GET).toString();
        } else {
            return aliOssProperties.getBucket() + "." + aliOssProperties.getEndpoint() + "/" + object;
        }
    }

    @Override
    public String getName() {
        return StorageType.ALI_OSS.name();
    }
}
